package psql_copy;

require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(   copy_table_with_progress_dots psql_copy_table_with_progress_dots);

use strict;
use warnings;

#_________________________________________________________________________________________

#copy_table_with_progress_dots

#calls postgres COPY function

#_________________________________________________________________________________________
sub copy_table_with_progress_dots($$$)
{
	my ($table_name, $data, $every) = @_;
	(my $line = <<"PL/SQLCMD") =~ s/^\s+//gm; print ($line);


							  --BEGIN
							  \\echo -n '\t\t['

							  COPY $table_name FROM stdin;
PL/SQLCMD

		my $line_cnt;
	my $dot_represents = $every;
	print STDERR "\t[";
	{
		open SQL_DATA, "$data" or
			die "Error:\nCould not open $data\n";
		while ( my $line = <SQL_DATA> )
		{
			print $line;
			$line_cnt++;
			if ( $line_cnt  % $dot_represents == 0 )
			{
				(my $line = <<"PL/SQLCMD") =~ s/^\s+//gm; print ($line);
				\\.
				\\echo -n .
				
				COPY $table_name FROM stdin;
PL/SQLCMD
					print STDERR "\n\t" if ( ($line_cnt / $dot_represents) % 50 == 0 );
				print STDERR '...' ;
			}
		}

	}

	($line = <<"PL/SQLCMD") =~ s/^\s+//gm; print ($line);
	\\.
	\\echo  ]
	
	--END

PL/SQLCMD
	print STDERR "]\n" ;

}

sub psql_copy_table_with_progress_dots($$$$$$)
{
	my ($table_name, $data, $every, $db_host, $db_name, $db_user) = @_;

	my $cmd = "psql ";
	$cmd .= "  -t -A -F \"\t\" ";
	$cmd .= "-h $db_host -d $db_name -U $db_user";
	open PSQL, "|$cmd" or die "Error\t\nCould not run [$cmd]\n";



	(my $line = <<"PL/SQLCMD" ) =~ s/^\s+//gm; print PSQL ($line);
	
	
	--BEGIN
	\\echo -n '\t\t['
	
	COPY $table_name FROM stdin;
PL/SQLCMD

		my $line_cnt;
	my $dot_represents = $every;
	{
		open SQL_DATA, "$data" or
			die "Error:\nCould not open $data\n";
		while ( my $line = <SQL_DATA> )
		{
			print PSQL $line;
			$line_cnt++;
			if ( $line_cnt  % $dot_represents == 0 )
			{
				(my $line = <<"PL/SQLCMD" ) =~ s/^\s+//gm; print PSQL ($line);
				\\.
PL/SQLCMD
				print PSQL "\\echo\n\\echo -n '\t\t'"
						if ( ($line_cnt / $dot_represents) % 50 == 0 );
				
				($line = <<"PL/SQLCMD" ) =~ s/^\s+//gm; print PSQL ($line);
				\\echo -n .
				COPY $table_name FROM stdin;
PL/SQLCMD
			}
		}

	}

	($line = <<"PL/SQLCMD") =~ s/^\s+//gm; print PSQL ($line);
	\\.
	\\echo  ]
	
	--END
	
PL/SQLCMD
		print STDERR "]\n" ;

}


1;
